package com.threez.common.security.config;

import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.same.SaSameUtil;
import cn.hutool.json.JSONUtil;
import com.threez.core.domain.R;
import com.threez.core.exception.enums.GlobalExceptionEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 权限安全配置
 *
 * @author Lion Li
 */
@AutoConfiguration
public class SecurityConfiguration implements WebMvcConfigurer {

    @Value("${module.token-validate}")
    private boolean tokenValidate;
    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注解拦截器
        if (tokenValidate){
            registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
        }
    }

    /**
     * 校验是否从网关转发
     */
    @Bean
    @ConditionalOnProperty(prefix = "module", name = "token-validate", havingValue = "true")
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/actuator/**")
                .setAuth(obj -> SaSameUtil.checkCurrentRequestToken())
//            .setError(e -> SaResult.error("认证失败，无法访问系统资源").setCode(HttpStatus.UNAUTHORIZED));
                .setError(e -> JSONUtil.toJsonStr(R.failEnum(GlobalExceptionEnum.UNAUTHORIZED_INTERFACE )));
    }
}
